package com.collectplus.express.parcel;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.TextAppearanceSpan;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.collectplus.express.R;
import com.collectplus.express.evaluate.EvaluateActivity;
import com.collectplus.express.evaluate.EvaluateCompleteActivity;
import com.collectplus.express.logic.AppLogic;
import com.collectplus.express.model.Const;
import com.collectplus.express.model.ParcelSendBean;
import com.collectplus.express.order.OrderPayActivity;
import com.shouhuobao.samecity.SameCityOrderActivity;

import java.util.ArrayList;

import droid.frame.activity.base.BaseAdapterExt;
import droid.frame.utils.android.Log;
import droid.frame.utils.lang.Str;

/**
 * 寄出的包裹/包裹搜索通用adapter
 *
 * @author kaka<br>
 *         2017-1-9下午4:33:22
 */
public class ParcelSendAdapter extends BaseAdapterExt<ParcelSendBean> {

    private OnClickListener listener;
    //用于退出activity,避免countdown，造成资源浪费。
    private SparseArray<CountDownTimer> countDownCounters;
    private CountDownTimer countDownTimer = null;

    public ParcelSendAdapter(ArrayList<ParcelSendBean> items, Activity context, OnClickListener listener) {
        super(items, context);
        this.listener = listener;
        //        this.countDownCounters = new SparseArray<>();
        if (!(context instanceof ParcelSearchActivity)) {
            setEmptyView(R.layout.parcel_check_empty);
        } else {
            setEmptyView(R.layout.app_empty_text);
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (hasEmptyView()) {
            return super.getView(position, convertView, parent);
        }
        ViewHolder holder = null;
        if (convertView == null || convertView.getTag() == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.parcel_all_send_item, null);
            holder.colorStatusView = (View) convertView.findViewById(R.id.color_status_view);
            holder.senderName = (TextView) convertView.findViewById(R.id.receiver_name);
            holder.senderAddress = (TextView) convertView.findViewById(R.id.receiver_address);
            holder.senderPhone = (TextView) convertView.findViewById(R.id.receiver_phone);
            holder.orderTime = (TextView) convertView.findViewById(R.id.order_time);
            holder.parcelStatus = (TextView) convertView.findViewById(R.id.parcel_status);
            holder.payHit = (TextView) convertView.findViewById(R.id.wait_pay);
            holder.oprateView = (TextView) convertView.findViewById(R.id.parcel_status_operate);
            holder.payOverWeight = (TextView) convertView.findViewById(R.id.parcel_over_weight);
            holder.cityWideOrOther = (ImageView) convertView.findViewById(R.id.city_wide_or_other);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        final ParcelSendBean parcel = items.get(position);
        holder.senderName.setText(parcel.getReceiverName());
        holder.senderAddress.setText(parcel.getReceiverAddress());
        holder.senderPhone.setText("联系电话：" + parcel.getReceiverPhone());
        holder.orderTime.setText("下单时间：" + parcel.getOrderTime());
        holder.oprateView.setText("");

        holder.payHit.setVisibility(View.GONE);
        holder.payOverWeight.setVisibility(View.GONE);
        holder.parcelStatus.setTextColor(context.getResources().getColor(R.color.app_font_1));

        colorStatusView(holder, parcel);
        // 补差价
        if (!Str.isEmpty(parcel.getOrderId2())) {
            handlePayOnclic(holder, parcel);
            holder.oprateView.setText("立即支付");
            holder.parcelStatus.setText("待支付超重价￥" + parcel.getOrder2Cost());
            holder.payOverWeight.setText("超" + parcel.getOrder2weight() + "公斤");
            holder.oprateView.setVisibility(View.VISIBLE);
            holder.payOverWeight.setVisibility(View.VISIBLE);
            // 订单取消
        } else if (parcel.getOrderStatus() == 10) {
            holder.colorStatusView.setBackgroundColor(Color.parseColor("#828C99"));
            if (parcel.getParcelStatus() == Const.ParcelStatus.unPayedCancel) {
                holder.parcelStatus.setText(parcel.getStatusDesc());
                holder.parcelStatus.setTextColor(Color.parseColor("#cacaca"));
                holder.oprateView.setVisibility(View.INVISIBLE);
            } //待更改

            // 火箭侠拒收
            else if (parcel.getParcelStatus() == Const.ParcelStatus.courierCancelOrder) {
                holder.parcelStatus.setText(parcel.getStatusDesc());
                holder.oprateView.setVisibility(View.INVISIBLE);
                holder.payOverWeight.setVisibility(View.VISIBLE);
                holder.payOverWeight.setText(parcel.getExceptionRemark());
                holder.payOverWeight.setTextColor(Color.parseColor("#cacaca"));
            } else {
                holder.parcelStatus.setText(parcel.getStatusDesc());
                holder.parcelStatus.setTextColor(Color.parseColor("#cacaca"));
                holder.oprateView.setVisibility(View.INVISIBLE);
            }
            // 待支付
        } else if (parcel.getParcelStatus() == Const.ParcelStatus.unpayed) {
            holder.payHit.setVisibility(View.VISIBLE);
            handlePayOnclic(holder, parcel);
            holder.oprateView.setText("去支付");
            holder.oprateView.setVisibility(View.VISIBLE);
            // 待寄出
            } else if (parcel.getParcelStatus() == Const.ParcelStatus.payed || parcel.getParcelStatus() == Const.ParcelStatus.pushed || parcel.getParcelStatus() == Const.ParcelStatus.poped
                || parcel.getParcelStatus() == 25 || parcel.getParcelStatus() == 26 || parcel.getParcelStatus() == Const.ParcelStatus.collectionsuccess) {
            if (parcel.getVisit() && parcel.getParcelStatus() == Const.ParcelStatus.payed) {
                holder.parcelStatus.setText(parcel.getStatusDesc());
                holder.oprateView.setVisibility(View.VISIBLE);
                holder.payOverWeight.setVisibility(View.VISIBLE);
                holder.oprateView.setText("选择投递点寄件");
                holder.payOverWeight.setText(parcel.getExceptionRemark());
                holder.payOverWeight.setTextColor(Color.parseColor("#cacaca"));
                holder.oprateView.setTag(parcel.getParcelId());
                holder.oprateView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.setClass(context, ParcelServicePointActivity.class);
                        intent.putExtra("orderId", parcel.getOrderId());
                        intent.putExtra("parcelId", parcel.getParcelId());
                        context.startActivity(intent);
                    }
                });
            } else if (parcel.getCityWide() && parcel.getParcelStatus() == Const.ParcelStatus.payed || parcel.getParcelStatus() == Const.ParcelStatus.collectionsuccess) {
                holder.parcelStatus.setText(parcel.getStatusDesc());
                holder.oprateView.setVisibility(View.VISIBLE);
                holder.oprateView.setText("火箭令牌");
                holder.oprateView.setTag(parcel.getParcelId());
                holder.oprateView.setOnClickListener(listener);
            }
            holder.parcelStatus.setText(parcel.getStatusDesc());
            holder.oprateView.setVisibility(View.VISIBLE);
            holder.oprateView.setText("火箭令牌");
            holder.oprateView.setTag(parcel.getParcelId());
            holder.oprateView.setOnClickListener(listener);
            // 已寄出
        } else if (parcel.getParcelStatus() == 200 || parcel.getParcelStatus() == 210) {
            handleEvaluate(holder, parcel);
        }
        //上门，同城方式下单的状态
        else if (parcel.getParcelStatus() == Const.ParcelStatus.visitParcel && (parcel.getVisit() || parcel.getCityWide())) {
            holder.parcelStatus.setText(parcel.getStatusDesc());
            holder.oprateView.setVisibility(View.VISIBLE);
            holder.oprateView.setText("火箭令牌");
            holder.oprateView.setTag(parcel.getParcelId());
            holder.oprateView.setOnClickListener(listener);
            if (parcel.getRemainingTime() > 0) {
                //显示倒计时
                holder.payOverWeight.setVisibility(View.VISIBLE);
                holder.payOverWeight.setTextColor(Color.parseColor("#E53131"));
                long conutDownInterval = 1000;
                remaintimeCountdown(holder.payOverWeight, parcel.getRemainingTime(), parcel);

                //                CountDownTimer countDownTimer = countDownCounters.get(holder.payOverWeight.hashCode());
                //将前一个缓存清除
                //                if (countDownTimer != null) {
                //                    countDownTimer.cancel();
                //                }
                final ViewHolder finalHolder = holder;
                countDownTimer = new CountDownTimer(parcel.getRemainingTime(), conutDownInterval) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        remaintimeCountdown(finalHolder.payOverWeight, millisUntilFinished, parcel);
                    }

                    @Override
                    public void onFinish() {
                        finalHolder.parcelStatus.setText("火箭侠上门已超时");
                        finalHolder.payOverWeight.setVisibility(View.GONE);
                        Log.d("11111", "倒计时完成");
                    }
                };
                countDownTimer.start();
                //                countDownCounters.put(holder.payOverWeight.hashCode(), countDownTimer);
            }

        }
        //用户主动取消
        else if (parcel.getParcelStatus() == Const.ParcelStatus.visitCancel) {
            holder.parcelStatus.setText(parcel.getStatusDesc());
            holder.parcelStatus.setTextColor(Color.parseColor("#cacaca"));
            holder.oprateView.setVisibility(View.INVISIBLE);
        }
        //火箭侠取消接收包裹
        else if (parcel.getParcelStatus() == Const.ParcelStatus.courierCancelOrder) {
            holder.parcelStatus.setText(parcel.getStatusDesc());
            holder.oprateView.setVisibility(View.INVISIBLE);
            holder.payOverWeight.setVisibility(View.VISIBLE);
            holder.payOverWeight.setText(parcel.getExceptionRemark());
            holder.payOverWeight.setTextColor(Color.parseColor("#cacaca"));
        }
        return convertView;
    }

    /**
     * 左侧颜色块
     */
    private void colorStatusView(ViewHolder holder, ParcelSendBean parcel) {
        if (parcel.getCityWide()) {
            holder.colorStatusView.setBackgroundColor(Color.parseColor("#FFE226"));
            holder.cityWideOrOther.setImageResource(R.drawable.city_wide_icon);
        } else {
            holder.colorStatusView.setBackgroundColor(Color.parseColor("#E53131"));
            holder.cityWideOrOther.setImageResource(R.drawable.national_icon);
        }
    }

    /**
     * 评价/已评价处理
     *
     * @param holder
     * @param parcel
     */
    private void handleEvaluate(ViewHolder holder, final ParcelSendBean parcel) {
        final Intent intent = new Intent();
        if (parcel.getParcelStatus() == 200) {
            holder.oprateView.setVisibility(View.VISIBLE);
            holder.parcelStatus.setText("包裹已被收件人签收");
            holder.oprateView.setText("服务评价");
            intent.setClass(context, EvaluateActivity.class);
            intent.putExtra("orderId", parcel.getOrderId());
        } else {
            holder.parcelStatus.setText("包裹已被收件人签收");
            holder.oprateView.setVisibility(View.VISIBLE);
            holder.oprateView.setText("已评价");
            intent.setClass(context, EvaluateCompleteActivity.class);
            intent.putExtra("orderId", parcel.getOrderId());
        }
        holder.oprateView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                context.startActivity(intent);
            }
        });

    }

    /**
     * 处理支付相关的按钮
     *
     * @param holder
     * @param item
     */
    private void handlePayOnclic(ViewHolder holder, final ParcelSendBean item) {
        try {
            if (Str.isEmpty(item.getOrderId2())) {
                String price = "￥" + Str.formatPrice(item.getCost());
                // 前后字体显示不同大小,判断小数点前面的位数
                Spannable span = new SpannableString(price);
                span.setSpan(new AbsoluteSizeSpan(13, true), 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                span.setSpan(new AbsoluteSizeSpan(16, true), 1, price.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                // TODO bug
                holder.parcelStatus.setText(span);
                if (item.getCityWide()) {
                    holder.oprateView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(context, SameCityOrderActivity.class);
                            intent.putExtra("orderId", item.getOrderId());
                            context.startActivity(intent);
                        }
                    });
                } else {
                    holder.oprateView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent();
                            intent.setClass(context, OrderPayActivity.class);
                            intent.putExtra("orderId", item.getOrderId());
                            context.startActivity(intent);
                        }
                    });
                }
            } else {// 补差价
                holder.oprateView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.setClass(context, OrderPayActivity.class);
                        intent.putExtra("orderId", item.getOrderId2());
                        intent.putExtra("isCover", 1);
                        context.startActivity(intent);
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 火箭侠上门倒计时
     */
    private void remaintimeCountdown(TextView countDown, long remainTime, ParcelSendBean parcel) {
        String[] diffs = AppLogic.getInstance().timeDiffStr(remainTime);
        String timeText = "";
        if (diffs.length == 0) {
            if (parcel.getVisit()) {
                timeText = "00时00分";
            } else {
                timeText = "00:00:00";
            }
        } else if (diffs.length == 1) {
            if (parcel.getVisit()) {
                timeText = "00时00";
            } else {
                timeText = "00:00:" + diffs[0];
            }
        } else if (diffs.length == 2) {
            if (parcel.getVisit()) {
                timeText = "00时" + diffs[0] + "分";
            } else {
                timeText = "00:" + diffs[0] + ":" + diffs[1];
            }
        } else if (diffs.length == 3) {
            if (parcel.getVisit()) {
                timeText = diffs[0] + "时" + diffs[1] + "分"+ diffs[2]+"秒";
            } else {
                timeText = diffs[0] + ":" + diffs[1] + ":" + diffs[2];
            }
        }
        int sencondStart = timeText.indexOf(":");
        SpannableString secondSp = new SpannableString(timeText);
        secondSp.setSpan(new TextAppearanceSpan(context, R.style.passport_count_down_style), sencondStart + 1, timeText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        countDown.setText(secondSp, TextView.BufferType.SPANNABLE);
    }

    class ViewHolder {
        TextView senderName;
        TextView senderAddress;
        TextView senderPhone;
        TextView orderTime;
        TextView parcelStatus;
        TextView payHit;
        TextView payOverWeight;
        TextView oprateView;
        View colorStatusView;
        ImageView cityWideOrOther;
    }

    /**
     * 清空资源
     */
    public void cancelAllTimers() {
        if (countDownCounters == null) {
            return;
        }
        for (int i = 0, length = countDownCounters.size(); i < length; i++) {
            CountDownTimer cdt = countDownCounters.get(countDownCounters.keyAt(i));
            if (cdt != null) {
                cdt.cancel();
            }
        }
    }
}
